// releasePage/components/ftContent/ftContent.js
const app = getApp();
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        ftScene: String,
        ftAddress: String,
        ftDiscription: String,
        ftSceneId: String,
        editId: String,
        ftOperator: String,
        ftOperatorId: String,
        // ftnetworktype: String,
        // ftoperatorinfo: String,
    },

    /**
     * 组件的初始数据
     */
    data: {
        edit: true,
        sceneImageArr: [], //上传照片
        // 图片描述
        description: [],
        // 当前描述索引
        currentDesIndex: 0,
        // 当前图片索引
        currentPicIndex: 0,
        // 是否展示图片预览
        showPreviewImg: false,
        // 是否展示输入框
        showTextarea: false,
        textareaValue: '',
        // 最大字数限制
        max: 100,
        // FT测试点
        ftlng: '',
        ftlat: '',
        ftGps: '',
        ftDescription: '',
        ftDescriptionlength: 0,
        city: '',
        country: '',
    },
    pageLifetimes: {
        show: function () {
            let _that = this;
            if (_that.data.ftScene && _that.data.ftOperator) {
                if (_that.data.ftGps && _that.data.ftAddress) {
                    _that.triggerEvent('btnEvent', 0); //通过triggerEvent将参数传给父组件
                }
            } else {
                this.triggerEvent('btnEvent', 100);
            }
            if (_that.data.editId && _that.data.edit) {
                _that.editContent();
            }
            _that.getFtNetWorkSceneList();
        },
    },
    /**
     * 组件的方法列表
     */
    methods: {
        //描述页面跳转
        discriptionTap(e) {
            wx.navigateTo({
                url: `../../pages/homePageInfo/description/description?current=0&description=${this.data.ftDiscription}`,
            });
        },
        ftSceneTap(e) {
            wx.navigateTo({
                url: `../../pages/homePageInfo/ftScene/ftScene`,
            });
        },
        addressTap(e) {
            wx.navigateTo({
                url: `../../pages/homePageInfo/address/address?current=0&address=${this.data.ftAddress}`,
            });
        },
        ftOperatorTap(e) {
            let operator = this.data.operatorId || '';
            wx.navigateTo({
                url: `../../pages/homePageInfo/operatorList/operatorList?operatorid=${operator}`,
                // url: `../../pages/operatorInfo/operatorInfo?type=01`
            });
        },
        //再次编辑
        editContent() {
            let _that = this;
            wx.request({
                url:
                    app.globalData.rootPath +
                    `cjMap/getFtSpecialLocationById?authId=${app.globalData.authId}&id=${_that.data.editId}`,
                method: 'GET',
                header: {
                    'content-type': 'application/json',
                },
                success: function (res) {
                    wx.setNavigationBarTitle({
                        title: '编辑/' + res.data.ftSpecialLocation.city,
                    });
                    _that.setData({
                        ftAddress: res.data.ftSpecialLocation.address,
                        ftlng: res.data.ftSpecialLocation.lng,
                        ftlat: res.data.ftSpecialLocation.lat,
                        city: res.data.ftSpecialLocation.city,
                        country: res.data.ftSpecialLocation.country,
                        ftGps:
                            res.data.ftSpecialLocation.lng.toFixed(1) +
                            '°E，' +
                            res.data.ftSpecialLocation.lat.toFixed(1) +
                            '°N',
                        ftScene: res.data.ftSpecialLocation.networkscene,
                        ftDiscription:
                            res.data.ftSpecialLocation.scenedescription,
                        ftSceneId: res.data.ftSpecialLocation.networksceneid,
                        ftOperator: '111',
                        edit: false,
                    });
                },
            });
        },
        // textarea聚焦隐藏提交按钮
        focusHideBtn() {
            this.triggerEvent('focusHideBtn');
        },
        // textarea失焦显示提交按钮
        blurShowBtn() {
            this.triggerEvent('blurShowBtn');
        },
        // GPS选择
        openLocation: function (e) {
            var _this = this;
            wx.chooseLocation({
                latitude: app.globalData.cityLat,
                longitude: app.globalData.cityLng,
                success: function (res) {
                    _this.setData({
                        ftAddress: res.address || res.name,
                        ftlng: res.longitude,
                        ftlat: res.latitude,
                        ftGps:
                            res.longitude.toFixed(1) +
                            '°E，' +
                            res.latitude.toFixed(1) +
                            '°N',
                    });
                },
                fail: function (res) {
                    console.log(res);
                },
            });
        },
        ftDescription(e) {
            this.setData({
                ftDescription: e.detail.value,
                ftDescriptionlength: e.detail.value.length,
            });
        },
        // 添加图片
        addImg(e) {
            const that = this;
            wx.chooseImage({
                count: 9 - that.data.sceneImageArr.length,
                success(res) {
                    let imgLen =
                        that.data.sceneImageArr.length +
                        res.tempFilePaths.length;
                    if (imgLen > 9) {
                        wx.showModal({
                            content: '最多上传8张图片，请重新上传',
                            showCancel: false,
                        });
                        return;
                    } else {
                        wx.showLoading({
                            title: '图片上传中',
                            mask: true,
                        });
                        const imgUploadResults = [];
                        let index = that.data.sceneImageArr.length;
                        for (let i = 0; i < res.tempFilePaths.length; i++) {
                            let imgUploadResult = app
                                .imgUpload(res.tempFilePaths[i])
                                .then((res) => {
                                    let num = i + index;
                                    that.data.sceneImageArr[num] = res;
                                    that.setData({
                                        sceneImageArr: that.data.sceneImageArr,
                                    });
                                    console.log(that.data.sceneImageArr);
                                });
                            imgUploadResults.push(imgUploadResult);
                        }
                        Promise.all(imgUploadResults).then((values) => {
                            wx.hideLoading();
                        });
                    }
                },
            });
        },
        // 删除图片
        deleteImg(e) {
            let index = e.currentTarget.dataset.index;
            console.log(index);
            this.data.sceneImageArr.splice(index, 1);
            // 如果该图片有图片描述也需要删除
            if (this.data.description[index]) {
                this.data.description.splice(index, 1);
            }
            this.setData({
                sceneImageArr: this.data.sceneImageArr,
                description: this.data.description,
            });
        },
        // 预览图片
        previewImgDes(e) {
            // let index = e.currentTarget.dataset.index;
            // this.setData({
            //     currentPicIndex: index
            // }, () => {
            //     wx.navigateTo({
            //         //hideBottom隐藏图片预览的删除按钮
            //         url: `../../../pages/checkIn/imgPreview/imgPreview?hideBottom=${true}`,
            //     })
            // })
        },

        addDescription(e) {
            let index = e.currentTarget.dataset.index;
            this.setData(
                {
                    currentDesIndex: index,
                },
                () => {
                    this.setData({
                        showTextarea: true,
                        textareaValue:
                            this.data.description[this.data.currentDesIndex] ||
                            '',
                    });
                }
            );
        },

        onBlur(e) {
            this.setData({
                showTextarea: false,
            });
        },

        onInput(e) {
            this.setData({
                textareaValue: e.detail.value,
            });
        },

        submitDescription() {
            this.data.description[this.data.currentDesIndex] =
                this.data.textareaValue;
            this.setData({
                description: this.data.description,
            });
        },
        // 提交
        submit(review) {
            let _that = this;
            if (_that.data.editId) {
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/editFtSpecialLocation?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: {
                        id: _that.data.editId,
                        delflg: '02', //删除标志 00未删除 01已删除 02待审核10草稿
                        networksceneid: _that.data.ftSceneId, //网络场景id
                        scenedescription: _that.data.ftDiscription, //描述说明
                        address: _that.data.ftAddress, //地址
                        lat: _that.data.ftlat,
                        lng: _that.data.ftlng,
                        city: _that.data.city || app.globalData.addressBack, //城市
                        country:
                            _that.data.country || app.globalData.countryBack, //国家
                        effectiveflg: '00',
                        curlat: app.globalData.locationLat,
                        curlng: app.globalData.locationLng,
                    },
                    success: function (res) {
                        console.log(res);
                        if (res.data.status == 0) {
                            if (review) {
                                app.doVerify(res.data.data.id, '01');
                            } else {
                                let pages = getCurrentPages(); //当前页面栈
                                let prevPage = pages[pages.length - 2]; //上一页面
                                prevPage.setData({
                                    //本页面数据赋值到上一个页面
                                    id: res.data.data.id,
                                });
                            }
                            wx.removeStorageSync('refreshMapPointId'); //刷新地图标记点
                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                duration: 2000,
                            });
                        } else {
                            wx.showToast({
                                title: '提交失败，请重新录入或联系后台管理',
                                icon: 'none',
                                duration: 2000,
                            });
                        }
                    },
                });
            } else {
                let picdescriptionArr = [];
                console.log(_that.data.description);
                for (let i = 0; i < _that.data.sceneImageArr.length; i++) {
                    picdescriptionArr.push(_that.data.description[i] || '');
                }
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/createFtSpecialLocation?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: {
                        delflg: '02', //删除标志 00未删除 01已删除 02待审核10草稿
                        networksceneid: _that.data.ftSceneId, //网络场景id
                        scenedescription: _that.data.ftDiscription, //描述说明
                        address: _that.data.ftAddress, //地址
                        lat: _that.data.ftlat,
                        lng: _that.data.ftlng,
                        city: app.globalData.addressBack, //城市
                        country: app.globalData.countryBack, //国家
                        effectiveflg: '00',
                        operator: _that.data.ftOperator, //运营商
                        cityoperatorid: _that.data.ftOperatorId, //运营商id
                        picurls: _that.data.sceneImageArr,
                        picdescriptions: picdescriptionArr,
                    },
                    success: function (res) {
                        console.log(res);
                        if (res.data.status == 0) {
                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                duration: 2000,
                            });
                        } else {
                            wx.showToast({
                                title: '提交失败，请重新录入或联系后台管理',
                                icon: 'none',
                                duration: 2000,
                            });
                        }
                    },
                });
            }
        },
        // 获取网络场景列表
        getFtNetWorkSceneList() {
            let _that = this;
            wx.request({
                url:
                    app.globalData.rootPath +
                    `cjMap/getFtNetWorkSceneList?authId=${app.globalData.authId}&createtimeorder=asc`,
                method: 'GET',
                header: {
                    'content-type': 'application/json',
                },
                success: function (res) {
                    console.log(res);
                    let value = [];
                    for (let i = 0; i < res.data.data.length; i++) {
                        value.push(res.data.data[i].networkscene);
                    }
                    if (
                        !value.includes(_that.data.ftScene) &&
                        _that.data.ftScene
                    ) {
                        wx.showToast({
                            title: '当前场景已被删除,请重新选择',
                            icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                            duration: 2000,
                        });
                        _that.setData({
                            ftScene: '',
                        });
                    }
                },
            });
        },
    },
});
